package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import bd.ConsultasTableModel;
import bd.Resultado;
import bd.Servicios;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class VentanaPagoCuotas extends javax.swing.JInternalFrame {
	private JLabel jnombre;
	private JPanel jPanel2;
	private Servicios serv;
	private JScrollPane jScrollPane;
	private JScrollPane jScrollPane1;
	private JButton pagar;
	private JPanel informacion;
	private JPanel cartel;
	private JPanel tablaImpagos;
	private JTable cuotasImpagas;
	private JLabel infoP;
	private JPanel pnlAux;
	private JPanel jPanel3;
	private JPanel Clientes;
	private JLabel buscar;
	private JTextField nrodoc;
	private JComboBox tipodoc;
	private JTable tabla;
	private int cliente;
	private Long prestamo;

	public VentanaPagoCuotas() {
		super();
		serv = Servicios.getServicios();
		initGUI();
	}

	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(741, 471));
			this.setBounds(0, 0, 741, 471);
			BorderLayout thisLayout = new BorderLayout();
			getContentPane().setLayout(thisLayout);
			this.setVisible(false);
			{
				jPanel2 = new JPanel();
				BorderLayout jPanel2Layout = new BorderLayout();
				getContentPane().add(jPanel2, BorderLayout.NORTH);
				jPanel2.setPreferredSize(new java.awt.Dimension(730, 62));
				jPanel2.setLayout(jPanel2Layout);
				jPanel2.setBounds(0, 0, 730, 62);
				{
					jnombre = new JLabel();
					jPanel2.add(jnombre, BorderLayout.NORTH);
					jnombre.setText("Empleado: ");
					jnombre.setBounds(17, 5, 701, 17);
					jnombre.setHorizontalTextPosition(SwingConstants.CENTER);
					jnombre.setHorizontalAlignment(SwingConstants.CENTER);
					jnombre.setPreferredSize(new java.awt.Dimension(730, 28));
				}
				{
					pnlAux = new JPanel();
					jPanel2.add(pnlAux, BorderLayout.CENTER);
					{
						buscar = new JLabel();
						pnlAux.add(buscar);
						buscar.setText("Buscar Cliente");
						buscar.setBounds(22, 34, 145, 17);
						buscar.setFont(new java.awt.Font("DejaVu Serif", 0, 14));
						buscar.setHorizontalAlignment(SwingConstants.CENTER);
					}
					{
						ComboBoxModel tipoModel = new DefaultComboBoxModel(
								new String[] { "" });
						tipodoc = new JComboBox();
						pnlAux.add(tipodoc);
						tipodoc.setModel(tipoModel);
						tipodoc.setBounds(173, 28, 108, 28);
					}
					{
						nrodoc = new JTextField();
						pnlAux.add(nrodoc);
						nrodoc.setBounds(293, 29, 173, 28);
						nrodoc.setText("Nro Documento");
						nrodoc.setPreferredSize(new java.awt.Dimension(156, 25));
						nrodoc.addFocusListener(new FocusAdapter() {
							public void focusGained(FocusEvent evt) {
								nrodoc.setText("");
							}
						});
						nrodoc.addKeyListener(new KeyAdapter() {
							public void keyReleased(KeyEvent evt) {
								if (nrodoc.getText().equals(""))
									refresh(-1);
								else
									refresh(Integer.parseInt(nrodoc.getText()));
							}
						});
						nrodoc.addKeyListener(new KeyAdapter() {
							public void keyTyped(KeyEvent e) {
								char caracter = e.getKeyChar();

								if (((caracter < '0') || (caracter > '9'))
										&& (caracter != '\b' // BACK_SPACE
										)) {
									e.consume(); // ignorar el evento de teclado
								}
							}
						});

					}
				}
			}

			{
				Clientes = new JPanel();
				BorderLayout ClientesLayout = new BorderLayout();
				Clientes.setLayout(ClientesLayout);
				getContentPane().add(Clientes, BorderLayout.CENTER);
				Clientes.setBounds(0, 62, 730, 100);
				{
					jScrollPane = new JScrollPane();
					Clientes.add(jScrollPane, BorderLayout.CENTER);
					jScrollPane.setBounds(0, 0, 730, 100);
					jScrollPane.setPreferredSize(new java.awt.Dimension(730,
							131));
					{
						TableModel tablaModel = new DefaultTableModel(
								new String[][] { {}, {} }, new String[] {});
						tabla = new JTable();
						jScrollPane.setViewportView(tabla);
						tabla.setAutoCreateRowSorter(true);
						tabla.setModel(tablaModel);
						tabla.addMouseListener(new MouseAdapter() {
							@Override
							public void mouseReleased(MouseEvent arg0) {
								int row = tabla.rowAtPoint(arg0.getPoint());
								Long value = (Long) tabla.getValueAt(row, 0);

								if (value != null) {
									pagar.setEnabled(false);
									verificarCliente(value.intValue());
								}

							}
						});
					}

				}
			}
			{
				jPanel3 = new JPanel();
				BorderLayout jPanel3Layout = new BorderLayout();
				getContentPane().add(jPanel3, BorderLayout.SOUTH);
				jPanel3.setLayout(jPanel3Layout);
				jPanel3.setBounds(0, 162, 730, 282);
				jPanel3.setPreferredSize(new java.awt.Dimension(730, 280));
				{
					cartel = new JPanel();
					BorderLayout cartelLayout = new BorderLayout();
					cartel.setLayout(cartelLayout);
					jPanel3.add(cartel, BorderLayout.NORTH);
					cartel.setPreferredSize(new java.awt.Dimension(730, 47));
					{
						infoP = new JLabel();
						cartel.add(infoP);
						infoP.setText("Detalles: Cuotas Impagas.");
						infoP.setBounds(12, 7, 706, 15);
						infoP.setHorizontalAlignment(SwingConstants.CENTER);
						infoP.setHorizontalTextPosition(SwingConstants.CENTER);
						infoP.setPreferredSize(new java.awt.Dimension(730, 26));
					}
				}
				{
					tablaImpagos = new JPanel();
					BoxLayout jPanel1Layout = new BoxLayout(tablaImpagos,
							javax.swing.BoxLayout.X_AXIS);
					tablaImpagos.setLayout(jPanel1Layout);
					jPanel3.add(tablaImpagos, BorderLayout.CENTER);
					{
						jScrollPane1 = new JScrollPane();
						tablaImpagos.add(jScrollPane1);
						jScrollPane1.setBounds(-2, 28, 730, 150);
						jScrollPane1.setPreferredSize(new java.awt.Dimension(
								730, 111));
						{
							TableModel jTable1Model = new DefaultTableModel(
									new String[][] { {}, {} }, new String[] {});
							cuotasImpagas = new JTable();
							jScrollPane1.setViewportView(cuotasImpagas);
							cuotasImpagas.setModel(jTable1Model);
							cuotasImpagas.setAutoCreateRowSorter(true);
							cuotasImpagas.addMouseListener(new MouseAdapter() {
								public void mouseReleased(MouseEvent arg0) {
									int row = cuotasImpagas.rowAtPoint(arg0
											.getPoint());
									Long value = (Long) cuotasImpagas
											.getValueAt(row, 0);

									if (value != null)
										pagar.setEnabled(true);
								}

							});
						}
					}
				}
				{
					informacion = new JPanel();
					jPanel3.add(informacion, BorderLayout.SOUTH);
					informacion.setLayout(null);
					informacion
							.setPreferredSize(new java.awt.Dimension(730, 99));
					{
						pagar = new JButton();
						informacion.add(pagar);
						pagar.setText("Pagar");
						pagar.setBounds(328, 27, 83, 34);
						pagar.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								pagarActionPerformed();
							}
						});
						pagar.setEnabled(false);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void refresh(int nro) {
		jnombre.setText("Empleado: " + serv.getEmpleado() + ". Legajo: "
				+ serv.getLegajo() + ".");
		ComboBoxModel tipoModel = new DefaultComboBoxModel(serv.getTipoDoc());
		tipodoc.setModel(tipoModel);

		Resultado r;
		if (nro == -1) {
			r = serv.realizarConsulta("SELECT nro_cliente, apellido, nombre, tipo_doc, nro_doc, fecha_nac, direccion, telefono FROM Cliente");
		} else {
			r = serv.realizarConsulta("SELECT nro_cliente, apellido, nombre, tipo_doc, nro_doc, fecha_nac, direccion, telefono FROM Cliente WHERE nro_doc like '"
					+ nro
					+ "%' and tipo_doc like '"
					+ tipodoc.getSelectedItem() + "'");
		}

		if (r.fueExitoso()) {
			ConsultasTableModel modelo = new ConsultasTableModel();

			String[] columnas = r.getColumnas();
			String[] tipo = r.getTipos();
			try {
				for (int i = 0; i < columnas.length; i++) {
					String columnaNombre = columnas[i];
					Class columnaTipo = Class.forName(tipo[i]);
					boolean columnaEditable = false;
					modelo.agregarColumna(columnaNombre, columnaTipo,
							columnaEditable);
				}

				tabla.setModel(modelo);

				Vector<Object[]> filas = r.getFilas();
				for (Object[] f : filas)
					if (f != null)
						((ConsultasTableModel) tabla.getModel()).addRow(f);
			} catch (ClassNotFoundException e) {

			}
		} else {
			JOptionPane.showMessageDialog(
					SwingUtilities.getWindowAncestor(this), r.getExcepcion()
							+ "\n", "Error al ejecutar la consulta.",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	private void verificarCliente(int cliente) {
		this.cliente = cliente;
		infoP.setText("Detalles: Cuotas Impagas. Cliente #" + cliente);

		Resultado r = serv
				.realizarConsulta("SELECT nro_prestamo, nro_pago as nro_cuota, valor_cuota as valor, fecha_venc FROM Prestamo NATURAL JOIN Pago WHERE nro_cliente ="
						+ cliente + " and fecha_pago is NULL");

		if (r.fueExitoso()) {
			ConsultasTableModel modelo = new ConsultasTableModel();

			String[] columnas = r.getColumnas();
			String[] tipo = r.getTipos();
			try {
				for (int i = 0; i < columnas.length; i++) {
					String columnaNombre = columnas[i];
					Class columnaTipo = Class.forName(tipo[i]);
					boolean columnaEditable = false;
					modelo.agregarColumna(columnaNombre, columnaTipo,
							columnaEditable);
				}

				cuotasImpagas.setModel(modelo);

				Vector<Object[]> filas = r.getFilas();
				for (Object[] f : filas)
					if (f != null) {
						prestamo = (Long) f[0];
						((ConsultasTableModel) cuotasImpagas.getModel())
								.addRow(f);
					}
			} catch (ClassNotFoundException e) {
			}
		} else {
			JOptionPane.showMessageDialog(
					SwingUtilities.getWindowAncestor(this), r.getExcepcion()
							+ "\n", "Error al ejecutar la consulta.",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	private void pagarActionPerformed() {
		int respuesta = JOptionPane.showConfirmDialog(null,
				"¿Registrar los pagos de la(s) cuota(s) seleccionadas?",
				"Confirmar pago", JOptionPane.YES_NO_OPTION,
				JOptionPane.QUESTION_MESSAGE);
		if (respuesta == 0) {
			int[] p = cuotasImpagas.getSelectedRows();
			int c = cuotasImpagas.getSelectedRowCount();
			Long[] pagos = new Long[c];
			int i;
			for (i = 0; i < c; i++)
				pagos[i] = (Long) cuotasImpagas.getValueAt(p[i], 1); // La
																		// columna
																		// 1 es
																		// la
																		// columna
																		// "nro_pago"
																		// segun
																		// la
																		// consulta
																		// realizada.

			boolean r = serv.realizarPago(pagos, prestamo);
			if (r) {
				verificarCliente(cliente);
				JOptionPane.showMessageDialog(this,
						"Se ha registrado el pago con éxito.", "Pago Exitoso",
						JOptionPane.INFORMATION_MESSAGE);
			} else
				JOptionPane.showMessageDialog(this,
						"Error al intentar realizar el pago.", "Falla",
						JOptionPane.ERROR_MESSAGE);
		}
	}
}